<template>
    <el-container style="min-height: 100vh">
        <el-container>
            <el-main v-if="roles === 'student'">
            <h1>你没有此操作</h1>
            </el-main>
            <el-main v-if="roles === 'superadmin'">
            <h1>你没有此操作</h1>
            </el-main>
            <el-main v-if="roles === 'admin'">
                <div style="margin: 10px 0">
                    <!-- <el-input style="width: 200px" placeholder="请输入宿舍类型 " suffix-icon="el-icon-message" v-model="category"
                        class="mll-5"></el-input> -->
                    <el-input style="width: 200px" placeholder="请输入学生姓名 " suffix-icon="el-icon-search"
                        v-model="name"></el-input>
                    <el-button class="mll-5" type="primary" @click="load">搜索</el-button>
                    <el-button type="warning" @click="reset">重置</el-button>
                </div>
                <div  v-if="roles === 'admin'" style="margin: 10px 0">
                    <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
                </div>

                <el-table :data="tableData" border v-if="roles === 'admin'" stripe :header-cell-class-name="headerBg"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="stu_num" label="学号" width="75">
                    </el-table-column>
                    <el-table-column prop="name" label="姓名" width="100">
                    </el-table-column>
                    <el-table-column prop="floor_num" label="楼号" width="100">
                    </el-table-column>
                    <el-table-column prop="layer" label="楼层" width="100">
                    </el-table-column>
                    <el-table-column prop="room_num" label="宿舍号" width="100">
                    </el-table-column>
                    <el-table-column prop="time" label="入住时间" width="100">
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button type="success" @click="handleEdit(scope.row)">编辑 <i
                                    class="el-icon-edit"></i></el-button>
                            <!-- <el-popconfirm class="mll-5" confirm-button-text='确定' cancel-button-text='我再想想'
                                icon="el-icon-info" icon-color="red" title="您确定删除吗？" @confirm="del(scope.row.id)"> -->
                            <el-button type="danger" slot="reference" @click="handleDelete()">删除 <i
                                    class="el-icon-remove-outline"></i></el-button>
                            <!-- </el-popconfirm> -->
                            <el-dialog title="提示" :visible.sync="delVisibleaa" width="300px" center>

                                <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>

                                <span slot="footer" class="dialog-footer">

                                    <el-button @click="delVisibleaa = false">取 消</el-button>

                                    <el-button type="primary" @click="del(scope.row.stu_num)">确 定</el-button>

                                </span>

                            </el-dialog>

                        </template>
                    </el-table-column>
                </el-table>
                <div style="padding: 10px 0; text-align: center;">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="pageNum" :page-sizes="[5, 8, 10, 20]" :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper" >
                    </el-pagination>
                </div>


                ​ <el-dialog title="住宿信息" :visible.sync="dialogFormVisible" width="50%">
                    ​ <el-form label-width="80px" size="small">
                        ​ <el-form-item label="学号">
                            ​ <el-input v-model="form.stu_num" autocomplete="off"></el-input>
                            ​ </el-form-item>
                        ​ <el-form-item label="楼号">
                            ​ <el-input v-model="form.floor_num" autocomplete="off"></el-input>
                            ​ </el-form-item>
                        ​ <el-form-item label="楼层">
                            ​ <el-input v-model="form.layer" autocomplete="off"></el-input>
                            ​ </el-form-item>
                        ​ <el-form-item label="宿舍号">
                            ​ <el-input v-model="form.room_num" autocomplete="off"></el-input>
                            ​ </el-form-item>
                        <el-form-item label="入住时间">
                            <el-date-picker v-model="form.time" type="date" placeholder="选择日期" :start="1900"
                                :end="2030"></el-date-picker>
                        </el-form-item>
                        ​ </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="save">确 定</el-button>
                    </div> ​
                </el-dialog>

            </el-main>
        </el-container>
    </el-container>
</template>
  
<script>
import service from "@/utils/request";
import axios from 'axios'
import { mapGetters } from 'vuex'
export default {
    name: 'Floor',
    computed: {
    ...mapGetters([ 'user', 'avatar', "roles",'Token']),
    formattedBirth() {
      // 使用 moment.js 将日期格式化为年月日格式
      return moment(this.user.birth).format('YYYY-MM-DD');
    },
    roles() {
      // 假设你从 Vuex 的 getters 中获取 roles
      return this.$store.getters.roles;
    },
    token(){
      return state.user.token
    }
  },
    data() {
        return {

            delarr: [],//存放删除的数据
            multipleSelection: [],//多选的数据
            tableData: [],
            msg: "",//记录每一条的信息，便于取id
            name: "",
            stu_num: "",
            dialogFormVisible: false,
            pageNum: 1,
            pageSize: 5,
            total: 0,
            form: {},
            collapseBtnClass: 'el-icon-s-fold',
            isCollapse: false,
            logoTextShow: true,
            delVisibleaa: false,
            headerBg: 'headerBg',
            floor: {
        building: '',
        floor: null,
        room: '',
        sex: '',
        category: ''
      },
        }
    },
    created() {
        this.fetchadmininfo(this.user.admin_num);
        this.load();
    },
    methods: {
        fetchadmininfo(admin_num) {
      axios
        .get('http://localhost:9090/Floor', {
          params: {
            admin_num: admin_num,
          },
        })
        .then((response) => {
          const floorList = response.data;
          if (floorList.length > 0) {
            const floor = floorList[0];
            this.floor.building = floor.floor_num || '';
            this.floor.floor = floor.layer_amount || null;
            this.floor.room = floor.room_amount || '';
            this.floor.category = floor.category || '';
            this.floor.sex = floor.sex || '';
            this.load();
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
        handleSizeChange(pageSize) {
            console.log(pageSize)
            this.pageSize = pageSize
            this.load()
        },
        handleCurrentChange(pageNum) {
            console.log(pageNum)
            this.pageNum = pageNum
            this.load()
        },
        loadDataFromLocalStorage() {
            const storedData = localStorage.getItem('tableData'); // 从本地存储中获取数据
            if (storedData) {
                this.tableData = JSON.parse(storedData); // 将数据解析为对象，并赋值给 tableData
            }
        },
        load() {
            const params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                name: this.name,
                floor_num: this.floor.building
            };

            const queryString = Object.keys(params)
                .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(params[key]))
                .join("&");

            fetch(`http://localhost:9090/Stayinfo/page1?${queryString}`)
                .then(res => res.json())
                .then(res => {
                    // 处理字段格式
                    const dateFormatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
                    res.data.forEach(item => {

                        // 对其他字段进行处理...
                        // 示例：处理日期字段
                        if (item.time) {
                            const timeDate = new Date(item.time);
                            item.time = dateFormatter.format(timeDate);
                        }
                    });

                    console.log(res);
                    this.tableData = res.data;
                    this.total = res.total;
                    localStorage.setItem('tableData', JSON.stringify(res.data));
                });
        }
        ,
        reset() {
            this.name = ""
            this.load()
        },
        handleAdd() {
            this.dialogFormVisible = true
            this.form = {}
        },
        handleEdit(row) {
            this.form = row
            this.dialogFormVisible = true
        },
        save() {
            // Convert the time to the desired format
            const timeDate = new Date(this.form.time);
            const formattedTime = `${timeDate.getFullYear()}-${(timeDate.getMonth() + 1).toString().padStart(2, '0')}-${timeDate.getDate().toString().padStart(2, '0')}`;

            // Update the form object with the formatted time
            this.form.time = formattedTime;

            service
                .post("http://localhost:9090/Stayinfo", this.form)
                .then(res => {
                    if (res) {
                        this.$message.success("保存成功");
                        this.dialogFormVisible = false;
                        this.load();
                    } else {
                        this.$message.error("保存失败");
                    }
                })
                .catch(error => {
                    this.$message.error("保存失败：" + error);
                });
        }
        ,

        handleDelete() {
            this.delVisibleaa = true;
        },
        del(stu_num) {
            service.delete("http://localhost:9090/Stayinfo/delete?stu_num=" + stu_num).then(res => {
                if (res) {
                    this.$message.success("删除成功")
                    this.delVisibleaa = false
                    this.load()
                } else {
                    this.$message.error("删除失败")
                }
            })
        },

        handleSelectionChange(val) {
            console.log(val)
            this.multipleSelection = val
        }
    }
}
</script>
  
<style>
.headerBg {
    background: #eee !important;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.mll-5 {
    margin-left: 5px;
}
</style>
  